package com.hzzc.core.service;

import com.hzzc.core.dao.SSOApplicationRoleResourcesMapper;
import com.hzzc.core.model.SSOApplicationRoleResources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zmm
 * 角色与资源，资源操作管理服务
 */
@Service
public class RoleResourceRelationService {

    @Autowired
    private SSOApplicationRoleResourcesMapper ssoApplicationRoleResourcesMapper;

    /**
     * 根据角色Id获取所有的资源Id
     *
     * @param roleId
     * @return
     */
    public Set<Long> getRoleResourceIds(Long appId, Long roleId) {
        Example example = new Example(SSOApplicationRoleResources.class);
        example.createCriteria().andEqualTo("applicationId", appId).andEqualTo("roleId", roleId);
        return ssoApplicationRoleResourcesMapper.selectByExample(example).stream().map(SSOApplicationRoleResources::getResourceId).collect(Collectors.toSet());
    }

    /**
     * 根据角色Id获取所有的资源Id
     *
     * @param roleId
     * @return
     */
    public Set<Long> getRoleResourceIds(Long appId, Set<Long> roleId) {
        Example example = new Example(SSOApplicationRoleResources.class);
        example.createCriteria().andEqualTo("applicationId", appId).andIn("roleId", roleId);
        return ssoApplicationRoleResourcesMapper.selectByExample(example).stream().map(SSOApplicationRoleResources::getResourceId).collect(Collectors.toSet());
    }


    public void updateRoleResources(long appId, long roleId, Set<Long> resourceIds) {
        Example cleanExample = new Example(SSOApplicationRoleResources.class);
        cleanExample.createCriteria().andEqualTo("applicationId", appId).andEqualTo("roleId", roleId);
        ssoApplicationRoleResourcesMapper.deleteByExample(cleanExample);
        List<SSOApplicationRoleResources> ssoApplicationRoleResourcesList = new ArrayList();
        for (Long resourceId : resourceIds) {
            ssoApplicationRoleResourcesList.add(new SSOApplicationRoleResources().setApplicationId(appId).setResourceId(resourceId).setRoleId(roleId));
        }
        ssoApplicationRoleResourcesMapper.insertList(ssoApplicationRoleResourcesList);
    }
}
